package com.orange.user.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
@Slf4j
public class TokenUtil {
    private static final long EXPIRE_TIME = 144 * 60 * 60 * 1000; // 144个小时
    private static final String TOKEN_SECRET = "dmj&cxx";  // 密钥盐

    /**
     * 签名生成
     *
     * @param userAccount 用户名
     * @return token
     */
    public static String sign(String userAccount) {
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            return JWT.create()
                    .withIssuer("auth0")
                    .withClaim("userAccount", userAccount)
                    .withExpiresAt(expiresAt)
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e) {
            log.error("token生成失败", e);
            throw new RuntimeException("token生成失败");
        }
    }

    /**
     * 签名验证
     *
     * @param token token字符串
     * @return DecodedJWT 解析后的JWT对象
     */
    public static DecodedJWT verify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET))
                    .withIssuer("auth0")
                    .build();
            return verifier.verify(token);
        } catch (Exception e) {
            log.error("token验证失败", e);
            throw new RuntimeException("token无效");
        }
    }

    /**
     * 从token中获取用户账号
     *
     * @param token token字符串
     * @return 用户账号
     */
    public static String getUserAccountFromToken(String token) {
        try {
            DecodedJWT jwt = verify(token);
            return jwt.getClaim("userAccount").asString();
        } catch (Exception e) {
            log.error("从token中获取用户账号失败", e);
            throw new RuntimeException("获取用户信息失败");
        }
    }
}
